package com.liusand.movement.interceptor;

import com.liusand.entity.pojo.User;
import com.liusand.movement.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author :liusha
 * packageName :com.liusand.user.interception
 * fileName :UserInterception
 * creationTime :2022/12/12 20:06
 */
@Slf4j
public class MovementInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader("Authorization");
//        JWT jwt = JWTUtil.parseToken(token);
//        jwt.setKey("sunchuangting".getBytes()).verify();
//        boolean timeVerifyResult = jwt.validate(0);
//        if(!timeVerifyResult){
//            throw new RuntimeException("token失效");
//        }
//        String id = (String) jwt.getPayload("id");
//        String phone = (String) jwt.getPayload("phone");
//        User user = new User();
//        user.setId(id);
//        user.setPhone(phone);
//        UserThreadLocalUtil.setThreadLocal(user);
        String id = request.getHeader("id");
        String phone = request.getHeader("phone");
        if(StringUtils.isEmpty(id) || StringUtils.isEmpty(phone)){
            int status = response.getStatus();
            log.info("{}",status);

            return false;
        }
        User user = new User();
        user.setId(id);
        user.setPhone(phone);
        UserThreadLocalUtil.setThreadLocal(user);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocalUtil.remove();
    }
}
